package mythreads;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class PollThreads {

	public static void main(String[] args) {
		ExecutorService es = Executors.newCachedThreadPool();
	    List<Callable<Integer>> tasks = new ArrayList<>();

	    for (int j = 1; j <= 10; j++) {
	        tasks.add(new Callable<Integer>() {

	            @Override
	            public Integer call() throws Exception {
	                int sum = 0;
	                System.out.println("Starting Thread "
	                        + Thread.currentThread().getId());

	                for (int i = 0; i < 1000000; i++) {
	                    sum += i;
	                }

	                System.out.println("Stopping Thread "
	                        + Thread.currentThread().getId());
	                return sum;
	            }

	        });
	    }

	    try {
	        List<Future<Integer>> futures = es.invokeAll(tasks);
	        int flag = 0;

	        for (Future<Integer> f : futures) {
	            Integer res = f.get();
	            System.out.println("Sum: " + res);
	            if (!f.isDone()) 
	                flag = 1;
	        }

	        if (flag == 0){
	            System.out.println("SUCCESS");
	            es.shutdown();
	            es.awaitTermination(1, TimeUnit.SECONDS);
	        }else{
	            System.out.println("FAILED");
	            es.shutdown();
	        }

	    } catch (InterruptedException | ExecutionException e) {
	        e.printStackTrace();
	    }

	}

}
